package com.cai.service.impl;

import com.cai.entity.DO.User;
import com.cai.entity.PO.MyPrincipal;
import com.cai.entity.PO.UserDetailsImpl;
import com.cai.service.PermissionService;
import com.cai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Title: UserDetailsServiceImpl
 * @Author RuoLi
 * @Package com.cai.service.impl
 * @Date 2024/1/12 10:39
 * @description: UserDetailsService实现类 实现loadUserByUsername验证用户
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsImpl userDetails = new UserDetailsImpl();
        //获取用户信息
        User user = userService.getUserByUsername(username);
        MyPrincipal myPrincipal=new MyPrincipal(user.getId(),user.getUsername());
        userDetails.setPassword(user.getPassword());
        userDetails.setMyPrincipal(myPrincipal);
        //获取用户的角色
        userDetails.setRole(userService.getRoleByUsername(username));
        //获取用户权限
        userDetails.setPermissions(permissionService.listPermissionsByUserName(username));

        return userDetails;
    }
}
